package com.example.jsruntimedemo.js.module;

import com.eclipsesource.v8.V8Object;
import com.example.jsruntimedemo.js.JsContext;
import com.example.jsruntimedemo.js.JsModule;

import java.util.ArrayList;
import java.util.List;

public class ModuleManager {
    public ModuleManager() {
    }

    private static class Holder {
        private static final ModuleManager INSTANCE = new ModuleManager();
    }

    public static ModuleManager getInstance() {
        return Holder.INSTANCE;
    }

    private final List<JsModule> moduleList = new ArrayList<>();
    private JsContext mJsContext;

    public void init(JsContext jsContext) {
        mJsContext = jsContext;
        moduleList.add(new UiModule());
        moduleList.add(new ConsoleModule());
        resgisterModules();
    }

    private void resgisterModules() {
        for (JsModule module : moduleList) {
            V8Object moduleObj = new V8Object(mJsContext.getEngine());
            for (String functionName : module.getFunctionName()) {
                moduleObj.registerJavaMethod((v8Object, params) -> {
                    module.excute(functionName, params);
                }, functionName);
            }
            mJsContext.getEngine().add(module.getName(), moduleObj);
        }
    }
}
